<template>
	<view>
		<navbar></navbar>
		<view v-if="!loading" class="container">
      <!-- 藏品信息 -->
      <view class="component">
        <view class="component-title f-32 f-bold col-accent">藏品信息</view>
        <view class="component-content goods">
          <view class="goods-header">
            <view class="dis-flex">
              <view class="goods__img-wrapper">
                <image class="goods__img" :src="other_info.goods_image" mode="aspectFill"></image>
              </view>
              <view class="goods-info flex-box m-left40">
                <view class="good__name f-32 twolist-hidden">{{ other_info.goods_name }}</view>
                <view class="goods-extra dis-flex flex-x-between flex-y-center">
                  <view class="col-9 f-24">{{ other_info.spec_value }}</view>
                  <view v-if="0 == other_info.order_total_price" class="col-m  good__price">免费</view>
                  <view v-else class="col-m good__price">￥{{ other_info.order_total_price }}</view>
                </view>
              </view>
            </view>
          </view>
          <!--  -->
        </view>
      </view>
      <!-- 支付方式 -->
      <view v-if="0 < other_info.order_total_price" class="component">
        <view class="component-title f-32 f-bold col-accent">支付方式</view>
        <view class="component-content pay-method">
          <button v-for="(item, key,index) in payTypes" :key="key" class="btn-normal " @tap.stop.prevent="onSelectPayType(item.value,index)" :class="index != typeindex  ?'Btm_boder':''">
                <view class="pay-item dis-flex flex-x-between">
                  <view class="item-left dis-flex flex-y-center">
                    <view :class="['item-left_icon',item.class]">
                      <text :class="[item.icon]"></text>
                    </view>
                    <view class="item-left_text">
                      <text>{{ item.name }}</text>
                    </view>
                  </view>
                  <view class="item-right" v-if="payTypeIndex == index">
                    <text class="iconfont icon-duihao col-m"></text>
                  </view>
                </view>
          </button>
        </view>
      </view>
      <!-- 底部操作栏 -->
      <bottom-placeholder></bottom-placeholder>
      <view class="footer-fixed f-30">
        <view class="footer-fixed-container dis-flex flex-x-between flex-y-center">
          <view class="dis-flex flex-y-center">
            <view v-if="0 == other_info.order_total_price" class="col-f good__price">免费</view>
            <view v-else class="col-f good__price">￥{{ other_info.order_total_price }}</view>
            <view class="count-down-wrapper">
              <text class="count-down-class">剩余</text>
              <count-down class="count-down-class" :serverTime="now_time" :startTime="end_time" formatType="1"
                          @finished="countdownFinished"></count-down>
            </view>
          </view>
          <button class="btn-normal btn-submit" @tap.stop.prevent="onSubmitOrder"
                  :disabled="disabled || !address_info || (address_info && !address_info.address_id)">去付款</button>
        </view>
      </view>
    </view>
    <security-password :show="securityPassword.show" @close="onToggleSecurityPassword" @success="onSecurityPasswordSuccess"></security-password>
	<input-alert ref="qrcode" :show="inputAlert.show" title="请输入验证码" placeholder="验证码" :params="inputAlert.params"
		@cancel="onInputAlertCancel" @confirm="onInputAlertConfirm"></input-alert>
		<view class="zz" v-show="isPwd">
			<view class="popup">
				<view class="title">
					交易密码
				</view>
				<view class="pwd">
					<!-- #ifndef APP-PLUS -->
					<PwdControl />
					<!-- #endif -->
				</view>
				<view class="btn" style="border-top:1rpx solid #dfdfdf;height: 100rpx;text-align: center;line-height: 100rpx;">
					<view @click="isPwd = false" style="width: 295rpx;height: 100%;border-right: 1rpx solid #dfdfdf;">取消</view>
					<view v-if="!disabled" @click="requestPayOrder" style="width: 300rpx;height: 100%;color: #007aff;">确定</view>
					<view v-else style="width: 300rpx;height: 100%;color: #999;">确定</view>
				</view>
			</view>
		</view>
  </view>
</template>

<script>
	import navbar from "@/components/navbar/navbar";
	import countDown from '@/components/count-down/index';
	import bottomPlaceholder from '@/components/bottom-placeholder/index';
	const app = getApp(); // 枚举类：支付方式
	import {
		isWeixin
	} from '@/utils/verify.js';
	import {
		payTypes
	} from '@/module.js';
	import PayTypeEnum from '@/utils/enum/PayType.js';
	import paymentUtils from '@/utils/paymentUtils.js';
	// #ifndef APP-PLUS
	import PwdControl from '@/components/PwdControl/index.vue';
	// #endif
	export default {
		components: {
			navbar,
			countDown,
			bottomPlaceholder,
			// #ifndef APP-PLUS
			PwdControl
			// #endif
		},
		data() {
			return {
				recharge: {},
				// 选中的支付方式 默认第一个
				payTypeIndex: 0,
				userInfo: uni.getStorageSync('userInfo'),
				payTypes: payTypes,
				// 当前页面参数
				options: {},
				address_info: null,
				// 默认收货地址
				// 禁用submit按钮
				disabled: false,
				loading: true,
				other_info: {
					goods_image: '',
					goods_name: '',
					spec_value: '',
					order_total_price: 0,
					create_time: '',
					publisher_name: ''
				},

				now_time: 0,
				end_time: 0,
				curPayType: '130',
				securityPassword: {
					show: false,
				},
				inputAlert: {
					show: false,
					params: null,
				},
				typeindex: 0,
				isPwd: false, //密码控件弹窗
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(e) {
			try {
				let _this = this;

				let options = JSON.parse(e.params); // 当前页面参数
				_this.setData({
					options
				});

				// console.log(options);
				_this.getOrderData();
			} catch (error) {
				console.log(error);
			} // 地址添加成功
			this.getBankList();
			this.addAddressSuccessCallback = () => {
				this.getOrderData();
			};
			// #ifndef APP-PLUS
			
			this.$nextTick(() => {
				window.pwdcontrol = undefined
				window.getRandom()
			})
			// #endif
			this.typeindex = Object.values(payTypes).length - 1
			if (Object.values(payTypes)[0]) {
				// this.curPayType = Object.values(payTypes)[0].value;
			}
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {},
		methods: {
			//校验密码

			// 获取银行卡列表 用于选择支付
			getBankList() {
				let _this = this
				let is_lianlian = uni.getStorageSync('isOpenStatus').is_open_lianlian
				if(!is_lianlian) return
				app._post_form('User/myAcctlist', {}, function(result) {
					if (1 == result.code) {
						let data = result.data
						// console.log(data)
						data.forEach((item, index) => {
							let payTypesItem = {}
							// _this.payTypes.push({canIUse:true,class:"LL_BALANCE",icon:"dy-iconfont icon-llbank",name:item.linked_brbankname,value:160});
							payTypesItem.canIUse = true
							payTypesItem.class = "LL_BALANCE"
							payTypesItem.icon = "dy-iconfont icon-llbank"
							payTypesItem.name = item.linked_brbankname + '(' + item.linked_acctno_pass +
								')'
							payTypesItem.linked_acctno = item.linked_acctno
							payTypesItem.value = 130
							// payTypes.push(payTypesItem)
							// Object.assign(_this.payTypes,{[index]:payTypesItem})
							_this.$set(_this.payTypes, index, payTypesItem)
							// 默认选择杉德支付
							// for (let key in _this.payTypes) {
							// 	// console.log(_this.payTypes[key]) // SHANDE
							// 	if(_this.payTypes[key].value == 170){
							// 		break;
							// 	}
							// 	_this.payTypeIndex +=1 
							// }
							
						})
						this.curPayType = payTypes[0].value
					}
				}, null, function() {
					// console.log(_this.payTypes)
				});
			},
			/**
			 * 选择支付方式
			 */
			onSelectPayType(value, index) {
				console.log(value)
				this.payTypeIndex = index
				this.curPayType = value;
				if (index == this.payTypes.length - 1) {
					console.log(this.payTypes['LL_BALANCE'])
				}

			},
			/**
			 * 获取当前订单信息
			 */
			getOrderData() {
				let _this = this;
				_this.loading = true;
				let options = _this.options; // 获取订单信息回调方法
				options.wsls = app.unCrypted('123456')
				let callback = (result) => {
					let resData = result.data; // 设置页面数据

					_this.setData(resData);
				};

				uni.showLoading({
					title: '加载中...'
				});
				// #ifndef MP
				options.is_h5 = 1;
				// #endif
				app._get(
					'order/addOrder',
					options,
					(result) => {
						callback(result);
					},
					() => {
						uni.navigateBack();
					},
					() => {
						_this.loading = false;
						uni.hideLoading();
					}
				);
			},

      //////// 安全密码回调 ////////
      // 切换密码弹窗的显示
      onToggleSecurityPassword: function () {
        this.securityPassword.show = !this.securityPassword.show;
      },
      // 密码输入正确
      onSecurityPasswordSuccess: function () {
        this.requestPayOrder();
      },
	  //////// 输入框弹窗回调 ////////
	  onInputAlertCancel: function() {
	  	this.onToggleInputAlert();
		// 跳转到订单
		this.redirectToOrderIndex();
	  },
	  onInputAlertConfirm: function(value, target, params) {
	  	this.requestValidationSms(value, params);
	  },
	  // 校验验证码
	  requestValidationSms: function(verify_code, params) {
		  let _this = this
		  let data = {
			sale_id: '',
		  	oid_partner: this.recharge.oid_partner,
		  	txn_seqno: this.recharge.order_no,
		  	total_amount: this.recharge.money,
		  	token: this.recharge.lianliantoken,
		  	verify_code: verify_code
		  }
		  // 校验验证码
		  app._post_form('user.dealer.recharge/sms', {
		  	data: JSON.stringify(data)
		  }, function(result) {
		  	if (1 == result.code) {
		  		// 隐藏验证码输入框
		  		_this.onInputAlertCancel();
		  		app.showToast('支付成功');
		  		this.redirectToOrderIndex();
		  	}
		  }, null, function() {
		  	_this.$refs.qrcode.over()
		  });
	  	// paymentUtils.requestLLBalancePay(verify_code, params, (res)=> {
	  	// 	// 支付成功
	  	// 	this.onToggleInputAlert();
	  	// 	app.showSuccessWithDuration(500, res.msg, () => {
	  	// 		this.redirectToOrderIndex();
	  	// 	});
	  	// });
	  },
	  onToggleInputAlert: function() {
	  	this.inputAlert.show = !this.inputAlert.show;
	  },

			/**
			 * 订单提交
			 */
			onSubmitOrder() {
				if (this.curPayType == '160') {
				  // 余额支付时需要输入安全密码
				  // this.onToggleSecurityPassword();
				  this.isPwd = true
				} else {
					this.requestPayOrder();
				}
			},
			requestPayOrder() {
				// #ifdef APP-PLUS
				console.log(this.curPayType)
				if(this.curPayType == '130' || this.curPayType == '170' || this.curPayType == '99'){
					let _this = this;
					if (_this.disabled) {
						return false;
					}
					// 按钮禁用, 防止二次提交
					_this.disabled = true;
					uni.showLoading({
						title: '正在处理...'
					});
					// console.log(_this.userInfo)
					// 订单提交
					let params = _this.pre_add_order_param;
					params.pay_type = _this.curPayType || 170;
					params.wsls = app.unCrypted('123456');
					params.id_no = _this.userInfo.address_default.ID_number || '';
					params.linked_acctname = _this.address_info.name || '';
					if (_this.payTypes[this.payTypeIndex]) {
						params.linked_acctno = _this.payTypes[this.payTypeIndex].linked_acctno || ''
					}
					// 付款发送验证码
					app._post_form('order/addOrder', params, function(result) {
						console.log(result)
						if(_this.curPayType == '170'){
							if(result.code == 1){
								console.log(result)
								app.navigationTo(result.data.pay_url)
							}else{
								app.showError(result.msg)
							}
						}else if(_this.curPayType == '99'){
							console.log(result)
						}else{
							if (8888 == result.data.payment.ret_code || result.data.payment.code == 1) {
								// 显示验证码弹窗
								_this.inputAlert.show = true;
								_this.recharge = result.data.payment.data || result.data.payment
							} else {
								if(result.data.payment.ret_code == '0000'){
									_this.isPwd = false
									app.showToast(result.data.payment.ret_msg)
									_this.redirectToOrderIndex();
								}else{
									app.showToast(result.data.payment.msg)
								}
							}
						}
						
					}, null, function() {
						uni.hideLoading();
						_this.disabled = false;
					});
				}else{
						app.showToast('密码输入错误')
				}
				// #endif
				// #ifndef APP-PLUS
				if(window.pwdcontrol || this.curPayType == '130' || this.curPayType == '170' || this.curPayType == '99'){
					let _this = this;
					if (_this.disabled) {
						return false;
					}
					// 按钮禁用, 防止二次提交
					_this.disabled = true;
					uni.showLoading({
						title: '正在处理...'
					});
					console.log(_this.userInfo)
					// 订单提交
					let params = _this.pre_add_order_param;
					params.pay_type = _this.curPayType;
					params.wsls = app.unCrypted('123456');
					params.id_no = _this.userInfo.address_default.ID_number;
					params.linked_acctname = _this.address_info.name;
					if(params.pay_type == 130){
						
					}else{
						params.password = window.pwdcontrol;
						params.random_key = window.random.random_key;
					}
					if (_this.payTypes[this.payTypeIndex]) {
						params.linked_acctno = _this.payTypes[this.payTypeIndex].linked_acctno
					}
					// 付款发送验证码
					app._post_form('order/addOrder', params, function(result) {
						if(_this.curPayType == '170'){
							if(result.code == 1){
								console.log(result.data.pay_url)
								app.navigationTo(result.data.pay_url)
							}else{
								app.showError(result.msg)
							}
							return 0
						}else if(_this.curPayType == '99'){
							if(result.data.payment.code == 1){
								app.navigationTo(result.data.payment.gateway_url)
							}else{
								app.showError(result.data.payment.msg)
							}
							
						}
						if (8888 == result.data.payment.ret_code || result.data.payment.code == 1) {
							// 显示验证码弹窗
							_this.inputAlert.show = true;
							_this.recharge = result.data.payment.data || result.data.payment
						} else {
							if(result.data.payment.ret_code == '0000'){
								_this.isPwd = false
								app.showToast(result.data.payment.ret_msg)
								_this.redirectToOrderIndex();
							}else{
								app.showToast(result.data.payment.msg)
							}
						}
					}, null, function() {
						uni.hideLoading();
						_this.disabled = false;
					});
				}else{
						app.showToast('密码输入错误')
				}
				// #endif
				
			},
			/**
			 * 跳转到未付款订单
			 */
			redirectToOrderIndex() {
				setTimeout(()=>{
					uni.redirectTo({
						url: '/pages/order/index'
					});
				},1000)
			},

			// 支付倒计时结束
			countdownFinished: function() {
				app.showError('提交超时，请重新下单', () => {
					uni.navigateBack();
				});
			}
		}
	};
</script>
<style lang="scss">
	page {
		background: #fff !important;
	}

	.zz{
		  position: fixed;
		  top: 0;
		  left: 0;
		  right: 0;
		  bottom: 0;
		  z-index: 14;
		  background: rgba(0, 0, 0, 0.5);
		  display: flex;
		  justify-content: space-around;
		  align-items: center;
		  z-index: 3;
		  .popup{
			  margin-top: 200rpx;
			  border-radius: 20rpx;
			  width: 600rpx;
			  height: 450rpx;
			  background-color: #fff;
			  display: flex;
			  flex-direction: column;
			  justify-content: space-between;
			  .title{
				  margin-top: 50rpx;
				  text-align: center;
				  height: 80rpx;
				  line-height: 80rpx;
				  // border-bottom: 1rpx solid #999;
			  }
			  .pwd{
				  margin-top: 50rpx;
				  width: 100%;
				  background-image: none !important;
				/deep/ Input{
					  width: 80% !important;
					  font-size: 30rpx;
					  height: 74rpx;
					  text-align: center;
					  background-color: #F8F5F5;
					  border-radius: 5rpx;
					  // border: 0.5rpx solid #999 !important;
				  }
				  
			  }
			  .btn{
				  display: flex;
			  }
		  }
	}
</style>
<style lang="scss" scoped>
	@import "./checkout.scss";
</style>
